import consumerRecoderModel from "../model/consumerRecoderModel";
import * as moment from 'moment';
import dTalkApi from "../core/dTalkApi";
import storeRecoderModel from "../model/storeRecoderModel";
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import visitMonthPlanModel from "../model/visitMonthPlanModel";
import visitMonthPlanService from "./visitMonthPlanService";

//拜访记录service
class VisitRecoder {
    constructor() { }

    //保存拜访记录
    async saveVisitRecoder(res: any) {
        let time = moment().format('YYYY-MM-DD:HH:mm');
        let month = moment().format('MM');
        let date = moment().format('YYYY-MM-DD');
        let date2 = moment(res.planDate).format('DD');
        let year= moment(res.planDate).format('YYYY');
        if (parseInt(moment(date).format('DD')) != parseInt(date2)) {
            await visitMonthPlanService.updatePlanStatus3(date, res.userid, res.consumerCode, res.consumerName, res.planType);
            return {code:2}
        } else {
            let time = moment().format('YYYY-MM-DD:HH:mm');
            let json: any = '';
            let access_token=await dTalkApiUtil.getAccessToken();
            let userInfo = await dTalkApi.getUserDetail(res.userid,access_token);
            let isChuchai: boolean = false;
            let city = userInfo.workPlace;
            if (res&&res.position.includes(city)) {
                isChuchai = false;
            } else {
                isChuchai = true;
            }
            //console.log('是否出差:'+isChuchai);
            //res.emplyId:拜访计划的id
            let data=await visitMonthPlanModel.findById({_id: res.emplyId});
            if(data&&data.visitRecoder){
                console.log('该计划已经有拜访记录!不能再次重复提交该计划的拜访记录!')
                return {code:3}
            }
            if (res&&(res.planType == '现有客户' || res.planType == '其他')) {
                if(res.planType == '现有客户'){
                    if((res.consumerCode)&&(res.consumerName)){
                        let a = await consumerRecoderModel.create({
                            planId: res.emplyId,
                            sourceId: res.userid + res.planDate,
                            //员工信息
                            userid: res.userid,//员工的userid
                            jobnumber: userInfo.jobnumber,//员工工号
                            userName: userInfo.name,//员工名字
                            //客户信息
                            consumerName: res.consumerName,
                            consumerCode: res.consumerCode,
                            consumerAddress:res.consumerAddress,//<--------------------------客户地址
                            city: '',//客户所在城市名称
                            cityType: '',//城市等级
                            typeOne: '',//类型1====customerType<-----visitMonthPlan
                            typeTwo: '',//类型2
                            typeThree: '',//类型3
                            typeFour: '', //类型4
                            //下面的为客户信息预留字段
                            typeFive: '',//类型5
                            typeSix: '',//类型6
                            typeSeven: '',//类型7
                            typeEight: '',//类型8
                            typeNine: '', //类型9
                            typeTen: '', //类型10
                            comment: 2,//说明  '导入的客户信息数据'与'拜访记录'
                            //拜访记录信息
                            timestamp: time,
                            month: month,
                            date: date,//写拜访记录的日期
                            planDate: res.planDate,//拜访日期
                            year:year,
                            consumerType: res.consumerType,
                            planType: res.planType,
                            planPurpose: res.planPurpose,//拜访计划的拜访目的
                            vistitWay: res.vistitWay,
                            position: res.position,
                            isChuchai: isChuchai,//是否出差
                            picture: res.picture,
                            purpose: res.purpose, //记录的拜访目的              
                            talkingPerson: res.talkingPerson,//洽谈姓名
                            job: res.job,//洽谈职位
                            connection: res.connection,//联系方式
                            visitResult: res.visitResult,//拜访结果
                            followMatter: res.followMatter,//跟进事宜
                            cooperation: ''
                        });
                        // console.log(a,'aaaaaaaaaaaaaaaaaaaaaaaa');
                        if(a){
                            let a_1=await visitMonthPlanModel.update({_id:res.emplyId}, { mark: 'green', visitRecoder: a._id },{upsert:true});
                            // console.log(' a_1 a_1 a_1 a_1 a_1 a_1 a_1:现有客户'+ a_1);
                        }
                        return {code:1}
                    }else{
                        console.log('客户编码或客户名称为空!!!')
                        return {code:0}
                    }
                }
                if( res.planType == '其他'){
                    if(res.planPurpose){
                        let data=await visitMonthPlanModel.findById({_id: res.emplyId});
                        if(data&&data.visitRecoder){
                            console.log('该计划已经有拜访记录!不能再次重复提交该计划的拜访记录!')
                            return {code:3}
                        }
                        let a = await consumerRecoderModel.create({
                            planId: res.emplyId,
                            sourceId: res.userid + res.planDate,
                            //员工信息
                            userid: res.userid,//员工的userid
                            jobnumber: userInfo.jobnumber,//员工工号
                            userName: userInfo.name,//员工名字
                            //客户信息
                            consumerName: res.consumerName,
                            consumerCode: res.consumerCode,
                            consumerAddress:res.consumerAddress,//<--------------------------客户地址
                            city: '',//客户所在城市名称
                            cityType: '',//城市等级
                            typeOne: '',//类型1====customerType<-----visitMonthPlan
                            typeTwo: '',//类型2
                            typeThree: '',//类型3
                            typeFour: '', //类型4
                            //==================================
                            //下面的为客户信息预留字段
                            typeFive: '',//类型5
                            typeSix: '',//类型6
                            typeSeven: '',//类型7
                            typeEight: '',//类型8
                            typeNine: '', //类型9
                            typeTen: '', //类型10
                            comment: 2,//说明  '导入的客户信息数据'与'拜访记录'
                            //拜访记录信息
                            timestamp: time,
                            month: month,
                            date: date,//写拜访记录的日期
                            planDate: res.planDate,//拜访日期
                            year:year,
                            consumerType: res.consumerType,
                            planType: res.planType,
                            planPurpose: res.planPurpose,//拜访计划的拜访目的
                            vistitWay: res.vistitWay,
                            position: res.position,
                            isChuchai: isChuchai,//是否出差
                            picture: res.picture,
                            purpose: res.purpose, //记录的拜访目的              
                            talkingPerson: res.talkingPerson,//洽谈姓名
                            job: res.job,//洽谈职位
                            connection: res.connection,//联系方式
                            visitResult: res.visitResult,//拜访结果
                            followMatter: res.followMatter,//跟进事宜
                            cooperation: ''
                        });
                        if(a){
                            let a_1=await visitMonthPlanModel.update({_id:res.emplyId}, { mark: 'green', visitRecoder: a._id,planStatus:'写好拜访记录' }, { upsert: true });
                            // console.log(' a_1 a_1 a_1 a_1 a_1 a_1 a_1:其他'+ a_1);
                        }
                        return {code:1}
                    }else{
                        console.log('拜访目的为空!!!!!!!')
                        return {code:0}
                    }
                }
            } else if (res&&res.planType == '新拓展客户') {
                if(res.consumerName){
                    let a = await consumerRecoderModel.create({
                        sourceId: res.userid + res.planDate,
                        planId: res.emplyId,
                        //员工信息
                        userid: res.userid,//员工的userid
                        jobnumber: userInfo.jobnumber,//员工工号
                        userName: userInfo.name,//员工名字
                        //客户信息
                        consumerName: res.consumerName,
                        consumerCode: res.consumerCode,
                        consumerAddress:res.consumerAddress,//<--------------------------客户地址
                        city: '',//客户所在城市名称
                        cityType: '',//城市等级
                        typeOne: '',//类型1====customerType<-----visitMonthPlan
                        typeTwo: '',//类型2
                        typeThree: '',//类型3
                        typeFour: '', //类型4
                        //==================================
                        //下面的为客户信息预留字段
                        typeFive: '',//类型5
                        typeSix: '',//类型6
                        typeSeven: '',//类型7
                        typeEight: '',//类型8
                        typeNine: '', //类型9
                        typeTen: '', //类型10
                        comment: 2,//说明  '导入的客户信息数据'与'拜访记录'
                        //拜访记录信息
                        timestamp: time,
                        month: month,
                        date: date,//写拜访记录的日期
                        planDate: res.planDate,//拜访日期
                        year:year,
                        planType: res.planType,//拜访类型
                        planPurpose: res.planPurpose,//拜访计划的拜访目的
                        consumerType: res.consumerType,
                        vistitWay: res.vistitWay,
                        position: res.position,
                        isChuchai: isChuchai,//是否出差
                        picture: res.picture,
                        purpose: res.purpose,  //记录的拜访目的          
                        talkingPerson: res.talkingPerson,//洽谈姓名
                        job: res.job,//洽谈职位
                        connection: res.connection,//联系方式
                        visitResult: res.visitResult,
                        followMatter: res.followMatter,
                        cooperation: res.cooperation //合作意向  
                    });
                    if(a){
                        let a_1= await visitMonthPlanModel.update({ _id: res.emplyId }, { mark: 'green', visitRecoder: a._id,planStatus:'写好拜访记录'  }, { upsert: true });
                    }
                    return {code:1}
                }else{
                    console.log('客户名称为空!!!!!!!!!!!!!')
                    return {code:0}
                }
            } else if (res&&res.planType == '门店') {
                let isliststample: boolean = false;
                let isliststandard: boolean = false;
                let islistletter: boolean = false;
                let list_letter: any = '';
                let json_sample: any = [];//样机列表
                if (res&&res.isListSample) {//是否有样机出样
                    isliststample = true;
                    if(res&&res.sampleList&&res.sampleList.length>0){
                        for (let index = 0; index < res.sampleList.length; index++) {
                            let sample = res.sampleList[index];
                            let pcSample:any[]=[];
                            sample.Picturesample.map(it=>{
                                pcSample.push(it)
                            })
                            json_sample[index] = {
                                sampleType: sample.sampleType,//样机型号
                                Picturesample: pcSample  //样机图片
                            }
                        };
                    }
                    
                    if (res&&res.listLetter != null) {//是否有陈列函
                        islistletter = true;
                        list_letter = res.listLetter;
                    } else {
                        list_letter = null;
                    }
                };
                if (res&&res.isListStandard) {//门店陈列是否达标
                    isliststandard = true;
                };
                //店内活动
                let pictureStoreActivity:any[]=[]
                if(res&&res.storeActivity){
                    if(res&&res.pictureStoreActivity){
                        let num_stoa= res.pictureStoreActivity.indexOf(',')
                        if(num_stoa==(-1)){
                            if(res.pictureStoreActivity.length){
                                let brand_pic2= res.pictureStoreActivity.substr(2,  res.pictureStoreActivity.length - 4)
                                pictureStoreActivity.push(brand_pic2)
                            }
                        }else{
                            if(res.pictureStoreActivity.length){
                                let posm= res.pictureStoreActivity.substr(1, res.pictureStoreActivity.length - 2)
                                let posm2=posm.split(',')
                                posm2.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    pictureStoreActivity.push(b)
                                }) 
                            }
                        }
                    }
                }
                let json1: any = [];
                let isListPart: boolean = false;
                let isListNewProduct: boolean = false;
                let json2: any = [];
                if (res&&res.storeType == '示范网吧') {
                    if(res&&res.mouseList&&res.mouseList.length>0){
                        for (let index = 0; index < res.mouseList.length; index++) {
                            let mouse = res.mouseList[index];
                            let pcSample:any[]=[];
                            mouse.mousePicture.map(it=>{
                                pcSample.push(it)
                            })
                            json2[index] = {
                                mousetype: mouse.mousetype,
                                mouseCount: mouse.mouseCount,
                                mousePicture:pcSample
                            }
                        };
                    }
                    let pictureBrand:any[]=[]
                    if(res&& res.pictureBrand){
                        let pictureBrand2:string=res.pictureBrand;
                        let num_brand= pictureBrand2.indexOf(',')
                        if(num_brand==(-1)){
                            if(res.pictureBrand.length){
                                let brand_pic2= res.pictureBrand.substr(2,  res.pictureBrand.length - 4)
                                pictureBrand.push(brand_pic2)
                            }
                        }else{
                            if(res.pictureBrand.length){
                                let brand_pic2= res.pictureBrand.substr(1,  res.pictureBrand.length - 2)
                                let brand_pic=brand_pic2.split(',')
                                brand_pic.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    pictureBrand.push(b)
                                }) 
                            }
                        }
                    }
                    json1 = {
                        mouseList: json2,
                        keyBoardTtype: res.keyBoardTtype,
                        brand: res.brand,
                        pictureBrand:pictureBrand//品牌专区照片
                    }
                } else{
                    //品牌专区形象照片2
                    let brandPicture:any[]=[]
                    if(res&&res.brandPicture){
                        let num_brand= res.brandPicture.indexOf(',')
                       let brandPicture_m:string=res.brandPicture;
                        if(num_brand==(-1)){
                            if(brandPicture_m.length){
                                let brand_pic2= brandPicture_m.substr(2,  res.brandPicture.length - 4)
                                brandPicture.push(brand_pic2)
                            }
                            
                        }else{
                            if(brandPicture_m.length){
                                let brand_pic2= brandPicture_m.substr(1,  res.brandPicture.length - 2)
                                let brand_pic=brand_pic2.split(',')
                                brand_pic.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    brandPicture.push(b)
                                }) 
                            }
                        }
                    }
                    //POSM形象照片
                    let picturePosm:any[]=[]
                    if(res&&res.picturePosm){
                        let num_posm= res.picturePosm.indexOf(',')
                        if(num_posm==(-1)){
                            if(res.picturePosm.length){
                                let brand_pic2= res.picturePosm.substr(2,  res.picturePosm.length - 4)
                                picturePosm.push(brand_pic2)
                            }
                        }else{
                            if(res.picturePosm.length){
                                let posm= res.picturePosm.substr(1, res.picturePosm.length - 2)
                                let posm2=posm.split(',')
                                posm2.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    picturePosm.push(b)
                                }) 
                            }
                        }
                    }
                    //画面形象照片
                    let pictureFrame:any[]=[]
                    if(res&&res.pictureFrame){
                        let num_frame= res.pictureFrame.indexOf(',')
                        if(num_frame==(-1)){
                            if(res.pictureFrame.length){
                                let brand_pic2= res.pictureFrame.substr(2,  res.pictureFrame.length - 4)
                                pictureFrame.push(brand_pic2)
                            }
                        }else{
                            if(res.pictureFrame.length){
                                let frame= res.pictureFrame.substr(1,  res.pictureFrame.length - 2)
                                let frame2=frame.split(',')
                                frame2.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    pictureFrame.push(b)
                                })
                            }
                        } 
                    }
                    //店招形象照片
                    let pictureStoreFigure:any[]=[]
                    if(res&&res.pictureStoreFigure){
                        let num_sto= res.pictureStoreFigure.indexOf(',')
                        let pictureStoreFigure_res:string=res.pictureStoreFigure
                        if(num_sto==(-1)){
                            if( res.pictureStoreFigure.length){
                                let brand_pic2= pictureStoreFigure_res.substr(2,  res.pictureStoreFigure.length - 4)
                                pictureStoreFigure.push(brand_pic2)
                            }
                        }else{
                            if( res.pictureStoreFigure.length){
                                let stof= res.pictureStoreFigure.substr(1,  res.pictureStoreFigure.length - 2)
                                let stof2=stof.split(',')
                                stof2.map(it=>{
                                    let b=it.substr(1,  it.length - 2)
                                    pictureStoreFigure.push(b)
                                })
                            }
                        }  
                    }
                    //是否有新品上架     
                    if (res&&res.isListNewProduct) {
                        isListNewProduct = true;
                        if(res&&res.newProductList&&res.newProductList.length>0){
                            for (let index = 0; index < res.newProductList.length; index++) {
                                let newProduct = res.newProductList[index];
                                let pcSample:any[]=[];
                                newProduct.pictureNewProduct.map(it=>{
                                    pcSample.push(it)
                                })
                                json2[index] = {
                                    newProductType: newProduct.newProductType,
                                    pictureNewProduct: pcSample
                                }
                            }
                        }
                    };
                    if (res&&(res.storeType == '模范店' || res.storeType == 'Gaming店')) {
                        //整柜照片
                        let pictureFullContainer:any[]=[]
                        if (res&&res.isListPart) {//是否陈列7节以上整柜--模范店   是否陈列3节以上整柜---Goming店
                            isListPart = true;
                            if(res&&res.pictureFullContainerList){
                                let num_picf= res.pictureFullContainerList.indexOf(',')
                                if(num_picf==(-1)){
                                    if(res.pictureFullContainerList.length){
                                        let brand_pic2= res.pictureFullContainerList.substr(2,  res.pictureFullContainerList.length - 4)
                                        pictureFullContainer.push(brand_pic2)
                                    }
                                }else{
                                    if(res.pictureFullContainerList.length){
                                        let posm= res.pictureFullContainerList.substr(1, res.pictureFullContainerList.length - 2)
                                        let posm2=posm.split(',')
                                        posm2.map(it=>{
                                            let b=it.substr(1,  it.length - 2)
                                            pictureFullContainer.push(b)
                                        }) 
                                    }
                                }
                            }
                        };
                        json1 = {
                            isListPart: isListPart,
                            pictureFullContainer: pictureFullContainer,//整柜照片
                            isListNewProduct: isListNewProduct,
                            newProductList: json2,//新品上架列表
                            brandPicture:brandPicture,//品牌专区形象照片2
                            picturePosm:picturePosm,//POSM形象照片
                            pictureFrame: pictureFrame,//画面形象照片
                            pictureStoreFigure: pictureStoreFigure //店招形象照片
                        }
                    } else if (res&&res.storeType == '时尚潮品店/智能馆/音乐店') {
                        let quarterNecessarySUK: boolean = false;
                        let pictureSUK:any[] = [];
                        //SUK照片
                        if (res&&res.quarterNecessarySUK) {
                            quarterNecessarySUK = true;
                            if(res&&res.pictureSUK){
                                let num_SUK= res.pictureSUK.indexOf(',')
                                if(num_SUK==(-1)){
                                    if(res.pictureSUK.length){
                                        let brand_pic2= res.pictureSUK.substr(2,  res.pictureSUK.length - 4)
                                        pictureSUK.push(brand_pic2)
                                    }
                                }else{
                                    if(res.pictureSUK.length){
                                        let brand_pic2= res.pictureSUK.substr(1,  res.pictureSUK.length - 2)
                                        let brand_pic=brand_pic2.split(',')
                                        brand_pic.map(it=>{
                                            let b=it.substr(1,  it.length - 2)
                                            pictureSUK.push(b)
                                        }) 
                                    }
                                }
                            }
                        };
                        let pictureFullContainer:any[]=[]
                        if (res&&res.isListPart) {//是否陈列2节以上整柜
                            isListPart = true;
                            if(res&&res.pictureFullContainer){
                                let num_picf= res.pictureFullContainer.indexOf(',')
                                if(num_picf==(-1)){
                                    if( res.pictureFullContainer.length){
                                        let brand_pic2= res.pictureFullContainer.substr(2,  res.pictureFullContainer.length - 4)
                                        pictureFullContainer.push(brand_pic2)
                                    }
                                }else{
                                    if( res.pictureFullContainer.length){
                                        let posm= res.pictureFullContainer.substr(1, res.pictureFullContainer.length - 2)
                                        let posm2=posm.split(',')
                                        posm2.map(it=>{
                                            let b=it.substr(1,  it.length - 2)
                                            pictureFullContainer.push(b)
                                        })  
                                    }
                                }
                            }
                        };
                        json1 = {
                            storeTypes: res.storeTypes,//APR  Music   IT Mall
                            quarterNecessarySUK: quarterNecessarySUK,
                            pictureSUK: pictureSUK,
                            isListPart: isListPart,
                            pictureFullContainer:pictureFullContainer,
                            isListNewProduct: isListNewProduct,
                            newProductList: json2,
                            brandPicture: brandPicture,//品牌专区形象照片2
                            picturePosm: picturePosm,//POSM形象照片
                            pictureFrame:pictureFrame,//画面形象照片
                            pictureStoreFigure: pictureStoreFigure //店招形象照片
                        }
                    } else if (res&&(res.storeType == 'A/B店' || res.storeType == 'LFR' || res.storeType == '其他')) {
                        let isListFocus: boolean = false;
                        let pictureListFocus:any[]=[]
                        if (res&&res.isListFocus) {//是否集中陈列
                            isListFocus = true;
                            if(res&&res.pictureListFocus){
                                let num_brand= res.pictureListFocus.indexOf(',')
                                if(num_brand==(-1)){
                                    if( res.pictureListFocus.length){
                                        let brand_pic2= res.pictureListFocus.substr(2,  res.pictureListFocus.length - 4)
                                        pictureListFocus.push(brand_pic2)
                                    }
                                }else{
                                    if( res.pictureListFocus.length){
                                        let brand_pic2= res.pictureListFocus.substr(1,  res.pictureListFocus.length - 2)
                                        let brand_pic=brand_pic2.split(',')
                                        brand_pic.map(it=>{
                                            let b=it.substr(1,  it.length - 2)
                                            pictureListFocus.push(b)
                                        }) 
                                    }
                                }
                            }
                        };
                        json1 = {
                            isListFocus: isListFocus,
                            pictureListFocus: pictureListFocus,
                            isListNewProduct: isListNewProduct,
                            newProductList: json2,
                            brandPicture: brandPicture,//品牌专区形象照片2
                            picturePosm: picturePosm,//POSM形象照片
                            pictureFrame: pictureFrame,//画面形象照片
                            pictureStoreFigure: pictureStoreFigure //店招形象照片
                        }
                    };
                }
                //保存门店的拜访记录
                if(res&&res.storeCode&&res.storeName){
                    let a = await storeRecoderModel.create({
                        sourceId: res.userid + res.planDate,
                        planId: res.emplyId,
                        timestamp: time,
                        userid: res.userid,//员工的userid
                        month: month,
                        date: date,
                        planDate: res.planDate,
                        year:year,
                        planType: res.planType,
                        storeName: res.storeName,
                        consumerAddress:res.consumerAddress,//<-------客户地址
                        storeCode: res.storeCode,
                        storeType: res.storeType,//示范网吧  模范店等
                        position: res.position,
                        isChuchai: isChuchai,//是否出差
                        isListSample: isliststample,
                        sampleList: json_sample,
                        isListStandard: isliststandard,
                        competitor: res.competitor,
                        storeActivity: res.storeActivity,
                        pictureStoreActivity: pictureStoreActivity,
                        picture: res.picture,//门头照片
                        isListLetter: islistletter,
                        listLetter: list_letter,
                        information: json1
                    });
                    if(a){
                        let a_1=  await visitMonthPlanModel.update({ _id: res.emplyId }, { mark: 'green', visitRecoder: a._id,planStatus:'写好拜访记录'  }, { upsert: true });
                    }
                    //  console.log(a,'a_a_a_a_a_a_a_a_a_a_a_a_a_a_')
                    return {code:1}
                }else{
                    console.log('门店名称或门店编码为空!!!!!!!!')
                    return {code:0}
                }
            } else {
                console.log('保存记录失败!!!!!!!!');
              return {code:0}
            }
           
        }
    }
    
    //关于陈列函的问题----员工拜访过此门店第一次过后,写拜访记录时再一次选择拜访该门店,
    //数据库中若有陈列函,查询返回陈列函,若无则返回空
    //storeName:门店名称  userid:员工id
    async listLetter(storeName: string, userid: string) {
        let json: any = {}
        let checkData = await storeRecoderModel.findOne({ userid: userid, storeName: storeName,isListLetter:true });
        if (checkData) {
            json = {listLetter: checkData.listLetter}
        } 
        return json;
    }

    //根据id查询拜访记录的详细信息
    async getRecoderById(id: string, planType: string) {
        if (planType == '门店') {
            let json = await storeRecoderModel.findById({ _id: id });
            return json;
        } else {
            let json = await consumerRecoderModel.findById({ _id: id });
            return json;
        }
    }



    
}
let visitRecoder = new VisitRecoder();
export default visitRecoder;
